/*
 * Copyright (C) 2024 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.wakala.employment.fragment.profile;

import static com.xuexiang.xui.utils.XToastUtils.toast;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.android.tu.loadingdialog.LoadingDailog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.github.gzuliyujiang.wheelpicker.BirthdayPicker;
import com.github.gzuliyujiang.wheelpicker.EthnicPicker;
import com.github.gzuliyujiang.wheelpicker.annotation.EthnicSpec;
import com.github.gzuliyujiang.wheelpicker.contract.OnDatePickedListener;
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionPickedListener;
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionSelectedListener;
import com.github.gzuliyujiang.wheelpicker.entity.EthnicEntity;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.BottomMenu;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.dialogs.InputDialog;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.kongzue.dialogx.interfaces.OnInputDialogButtonClickListener;
import com.kongzue.dialogx.interfaces.OnMenuItemClickListener;
import com.leaf.library.StatusBarUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.wakala.employment.R;
import com.wakala.employment.activity.MainActivity;
import com.wakala.employment.adapter.entity.User;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.core.http.subscriber.TipRequestSubscriber;
import com.wakala.employment.databinding.FragmentProfileBinding;
import com.wakala.employment.fragment.other.AboutFragment;
import com.wakala.employment.fragment.other.SettingsFragment;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.bean.FileResultVo;
import com.wakala.employment.http.bean.UserEditRequest;
import com.wakala.employment.utils.TokenUtils;
import com.wakala.employment.utils.Utils;
import com.wakala.employment.utils.XUtils;
import com.xuexiang.rxutil2.lifecycle.RxLifecycle;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.callback.impl.IProgressResponseCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.subsciber.ProgressLoadingSubscriber;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.textview.supertextview.SuperTextView;
import com.xuexiang.xutil.app.ActivityUtils;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.file.FileUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xuexiang
 * @since 2019-10-30 00:18
 */
@Page(anim = CoreAnim.none)
public class ProfileFragment extends BaseFragment<FragmentProfileBinding> implements SuperTextView.OnSuperTextViewClickListener {
    private static String TAG = ProfileFragment.class.getSimpleName();

    private List<LocalMedia> mSelectList = new ArrayList<>();

    LoadingDailog dialog;
    Boolean  cameraPermission = true;
    String cameraPermissionName=Permission.CAMERA;
    Boolean  storagePermission = true;
    String storagePermissionName = Permission.READ_MEDIA_IMAGES;


    @NonNull
    @Override
    protected FragmentProfileBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentProfileBinding.inflate(inflater, container, attachToRoot);
    }

    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle();
        titleBar.setTitle("个人资料设置");
        titleBar.setTitleColor(R.color.black);
        titleBar.setLeftTextColor(R.color.black);
        titleBar.setLeftImageDrawable(getResources().getDrawable(R.drawable.icon_arrow_back));
        titleBar.setBackgroundResource(R.color.white);//设置标题栏背景颜色
        StatusBarUtil.setDarkMode(getActivity());
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        return titleBar;
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initViews() {
        bindData(null);
        //初始化加载对话框
        initLoadingDialog();
    }

    private void initLoadingDialog(){
        LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(getContext())
                .setMessage("处理中...")
                .setCancelable(true)
                .setCancelOutside(true);
        dialog=loadBuilder.create();
    }

    private void bindData(User user){
        if(null==user){
            user = TokenUtils.getmLoginUser();
        }
        if(null==user){
            getLoginUserInfo();
        }
        //绑定数据
        //头像
        if(Utils.isHttpAddress(user.getAvatar())){
           // Uri uri = Uri.parse(user.getAvatar());
           // binding.rivHeadPic.setImageURI(uri);
            RequestOptions options = new RequestOptions()
                    .centerCrop()
                    .placeholder(R.color.color_f4)
                    .diskCacheStrategy(DiskCacheStrategy.ALL);
            Glide.with(binding.rivHeadPic.getContext()).load(user.getAvatar())
                    .apply(options)
                    .into(binding.rivHeadPic);
        }
        //账号
        binding.stAccount.setCenterString(user.getAccount());
        //名字
        binding.stModifyName.setCenterString(user.getNickname());
        //性别
        binding.stModifySex.setCenterString(user.getSexName());
        //民族
        binding.stModifyEthnic.setCenterString(user.getNation());
        //生日
        binding.stModifyBirthday.setCenterString(user.getBirthday());
        //会员编号
        binding.stUserMemberNo.setCenterString(user.getMemberNo());
        //手机号
        binding.stModifyPhone.setCenterString(user.getPhone());
        //注册时间
        binding.stRegisterTime.setCenterString(user.getRegisterTime());


    }

    @Override
    protected void initListeners() {
        binding.stModifyPhone.setOnSuperTextViewClickListener(this);
        binding.stModifyName.setOnSuperTextViewClickListener(this);
        binding.stModifySex.setOnSuperTextViewClickListener(this);
        binding.stModifyEthnic.setOnSuperTextViewClickListener(this);
        binding.stModifyBirthday.setOnSuperTextViewClickListener(this);
        binding.rivHeadPic.setOnClickListener(view -> checkPermission(cameraPermissionName));
    }

    @SingleClick
    @Override
    public void onClick(SuperTextView view) {
        int id = view.getId();
        if (id == R.id.st_modify_phone) {
            openNewPage(ModifyPhoneFragment.class);
        } else if (id == R.id.st_modify_name) {
            showModifyNameDialog();
        } else if (id == R.id.st_modify_sex) {
            modifySex();
        } else if (id == R.id.st_modify_ethnic) {
            modifyEthnic();
        } else if (id == R.id.st_modify_birthday) {
            // 出生年月
            modifyBirthday();

        } else if (id == R.id.riv_head_pic) {
            checkPermission(cameraPermissionName);

        }
    }

    private void checkPermission(String cameraPermissionName){
        checkPhonePermission(cameraPermissionName);
    }

    private void checkPhonePermission(String permission){
        //检查是否获取了定位权限
        if(XXPermissions.isGranted(getContext(), permission)) {
            //已获取权限
            modifyHeadPic();
            /*if(permission.equals(cameraPermissionName)){
                cameraPermission = true;
                modifyHeadPic();
            }else if(permission.equals(storagePermissionName)){
                storagePermission = true;
                modifyHeadPic();
            }*/

        }else {
            CustomDialog.show(new OnBindView<CustomDialog>(R.layout.layout_custom_permisstion_dialog) {
                @Override
                public void onBind(final CustomDialog dialog, View v) {
                    Button btnOk;
                    btnOk = v.findViewById(R.id.btn_ok);
                    TextView textClose = v.findViewById(R.id.btn_close);

                    textClose.setOnClickListener(view -> dialog.dismiss());
                    btnOk.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //申请权限
                            applyXXXPermission(permission);
                            dialog.dismiss();
                        }
                    });
                }
            }).setMaskColor(getResources().getColor(R.color.translucent_background));
        }
    }

    private void applyXXXPermission(String permission){
        XXPermissions.with(this)
                // 申请单个权限
                .permission(permission)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!allGranted) {
                            toast("获取部分权限成功，但部分权限未正常授予");
                            return;
                        }

                        //权限
                        if(permission.equals(cameraPermissionName)){
                            Toaster.show("已获取相机权限");
                            cameraPermission = true;
                        }else if(permission.equals(storagePermissionName)){
                            Toaster.show("已获取相册权限");
                            storagePermission = true;
                        }
                        modifyHeadPic();
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        if (doNotAskAgain) {
                            toast("被拒绝授权，请手动开启相机、相册权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(getContext(), permissions);
                        } else {
                            toast("获取相机权限失败");
                        }
                    }
                });
    }

    /**
     * 修改头像
     */
    private void modifyHeadPic(){
        XUtils.getPictureSelector(this)
                .selectionMedia(mSelectList)
                .maxSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    mSelectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia media = mSelectList.get(0);
                    String path = media.getPath();
                    RequestOptions options = new RequestOptions()
                            .centerCrop()
                            .placeholder(R.color.color_f4)
                            .diskCacheStrategy(DiskCacheStrategy.ALL);
                    Glide.with(binding.rivHeadPic.getContext()).load(path)
                            .apply(options)
                            .into(binding.rivHeadPic);
                    uploadImg(path);

                    break;
                default:
                    break;
            }
        }
    }

    private void modifyBirthday(){
        BirthdayPicker picker = new BirthdayPicker(getActivity());
        picker.setTitle("选择出生年月");
        picker.setDefaultValue(1991, 11, 11);
        picker.setOnDatePickedListener(new OnDatePickedListener() {
            @Override
            public void onDatePicked(int year, int month, int day) {
                //Toaster.show(year);
                String monthStr=month<10?"0"+month:month+"";
                String dayStr=day<10?"0"+day:day+"";
                binding.stModifyBirthday.setCenterString(year+"-"+monthStr+"-"+dayStr);
                UserEditRequest userEditRequest = new UserEditRequest();
                userEditRequest.setBirthday(year+"-"+monthStr+"-"+dayStr);
                userEdit(userEditRequest);
            }
        });
        picker.getWheelLayout().setResetWhenLinkage(false);
        picker.show();
    }

    /**
     * 修改名族
     */
    private void modifyEthnic() {
        EthnicPicker picker = new EthnicPicker(getActivity());
        picker.setTitle("选择民族");
        picker.setBodyWidth(140);
        picker.setEthnicSpec(EthnicSpec.SEVENTH_NATIONAL_CENSUS);
        picker.setDefaultValueByCode("01");
        picker.setDefaultValueByName("汉族");
        picker.setDefaultValueBySpelling("Unrecognized");
        picker.setOnOptionPickedListener(new OnOptionPickedListener() {
            @Override
            public void onOptionPicked(int position, Object item) {
                EthnicEntity ethnicEntity = (EthnicEntity)item;
                UserEditRequest userEditRequest = new UserEditRequest();
                userEditRequest.setNation(ethnicEntity.getName());
                userEdit(userEditRequest);
            }
        });
        picker.getWheelLayout().setOnOptionSelectedListener(new OnOptionSelectedListener() {
            @Override
            public void onOptionSelected(int position, Object item) {
                picker.getTitleView().setText(picker.getWheelView().formatItem(position));
                binding.stModifyEthnic.setCenterString(picker.getWheelView().formatItem(position));
            }
        });
        picker.show();
    }

    private void modifySex(){
        BottomMenu.show(new String[]{"男","女","保密"})
                .setMessage("选择性别").setCancelable(false).setCancelButton("取消")
                .setOnMenuItemClickListener(new OnMenuItemClickListener<BottomMenu>() {
                    @Override
                    public boolean onClick(BottomMenu dialog, CharSequence text, int index) {

                        UserEditRequest userEditRequest = new UserEditRequest();
                        userEditRequest.setSex(index+1);
                        userEdit(userEditRequest);
                        binding.stModifySex.setCenterString(text);
                        return false;
                    }
                });
    }
    private void showModifyNameDialog(){
        new InputDialog("请输入要修改的名称", "", "确定", "取消", binding.stModifyName.getCenterString())
                .setCancelable(false)
                .setOkButton(new OnInputDialogButtonClickListener<InputDialog>() {
                    @Override
                    public boolean onClick(InputDialog baseDialog, View v, String inputStr) {
                        //XToastUtils.toast("输入的内容：" + inputStr);
                        binding.stModifyName.setCenterString(inputStr);
                        UserEditRequest userEditRequest = new UserEditRequest();
                        userEditRequest.setNickname(inputStr);
                        userEdit(userEditRequest);
                        return false;
                    }
                })
                .show();
    }
    /**
    **
    * 根据token获取当前登录用户信息
     */
    @SuppressLint("CheckResult")
    private void getLoginUserInfo(){
        dialog.show();
        XHttpProxy.proxy(TestApi.IUserService.class)
                .getLoginUserInfo()
                .subscribeWith(new NoTipRequestSubscriber<User>() {
                    @Override
                    public void onSuccess(User user) {
                        dialog.dismiss();
                        TokenUtils.clearLoginUser();
                        TokenUtils.setmLoginUser(user);
                        bindData(user);
                    }
                    @Override
                    public void onError(ApiException e) {
                        dialog.dismiss();
                        super.onError(e);
                        ToastUtils.toast(e.getDisplayMessage());
                    }
                });
    }



    @SuppressLint("CheckResult")
    private void userEdit(UserEditRequest userEditRequest){
        dialog.show();
        XHttpProxy.proxy(TestApi.IUserService.class)
                .userEdit(userEditRequest)
                .subscribeWith(new NoTipRequestSubscriber() {

                    @Override
                    protected void onSuccess(Object o) {
                        Log.i(TAG,"-------------更新用户信息详情------------------");
                        dialog.dismiss();
                        Toaster.show("修改成功");
                        Log.i(TAG,"-------------更新用户信息详情------------------");
                        //更新用户信息缓存
                        getLoginUserInfo();
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        dialog.dismiss();
                        ToastUtils.toast(e.getDisplayMessage());
                        Log.i(TAG,"-------------更新用户信息详情-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                    }

                });
    }

    @SuppressLint("CheckResult")
    private void  uploadImg(String mPicturePath){
        dialog.show();
        XHttp.post("/api/front/user/upload/image")
                .params("model", "user").params("pid",7).accessToken(true)
                .uploadFile("file", FileUtils.getFileByPath(mPicturePath), new IProgressResponseCallBack() {
                    @Override
                    public void onResponseProgress(long bytesWritten, long contentLength, boolean done) {

                    }
                }).execute(FileResultVo.class)
                .compose(RxLifecycle.with(this).<FileResultVo>bindToLifecycle())
                .subscribeWith(new TipRequestSubscriber<FileResultVo>() {
                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        dialog.dismiss();
                    }

                    @Override
                    public void onSuccess(FileResultVo aBoolean) {
                        dialog.dismiss();
                        ToastUtils.toast("图片上传" + (aBoolean!=null ? "成功" : "失败") + "！");
                        UserEditRequest userEditRequest = new UserEditRequest();
                        userEditRequest.setAvatar(aBoolean.getUrl());
                        userEdit(userEditRequest);
                    }
                });
    }
}
